import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import twitter4j.GeoLocation;
import twitter4j.Location;
import twitter4j.ResponseList;
import twitter4j.Trend;
import twitter4j.Trends;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.internal.org.json.JSONException;
import twitter4j.internal.org.json.JSONObject;

public class TwitterLocationTrend {

	TwitterFactory tf;
	Twitter twitter;

	public TwitterLocationTrend() {
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true)
				.setOAuthConsumerKey("gzqIksq8Ibfi3EcLQeGh0A")
				.setOAuthConsumerSecret(
						"YUqzjBfDd6j2kTeOMfNB2mqoHH62pFTATYakWb8sk")
				.setOAuthAccessToken(
						"1539802722-0KoUclkm5TZmdL7ArQ4zDRh1Fld6O8hfaHa6tJg")
				.setOAuthAccessTokenSecret(
						"6K64QOGXCeqZwAnu9njeD0B8tXaME2w97T0YveA");
		TwitterFactory tf = new TwitterFactory(cb.build());
		twitter = tf.getInstance();
	}

	public Trend[] getTrends(String city) throws TwitterException, IOException,
			JSONException {
		double lon, lat;

		JSONObject json = readJsonFromUrl("http://maps.googleapis.com/maps/api/geocode/json?address="
				+ city + "&sensor=false");
		String toParse = json.toString();
		String lonString, latString;

		int lngI = toParse.indexOf("lat");
		int latI = toParse.indexOf("lng");

		lonString = toParse.substring(lngI + 5, lngI + 13);
		latString = toParse.substring(latI + 5, latI + 13);

		lon = Double.parseDouble(lonString);
		lat = Double.parseDouble(latString);

		GeoLocation gl = new GeoLocation(lon, lat);
		ResponseList<Location> rl = twitter.getClosestTrends(gl);
		Location l = rl.get(0);

		Trends t = twitter.getPlaceTrends(l.getWoeid());

		Trend[] trends = t.getTrends();

		return trends;
	}

	private static String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}

	public static JSONObject readJsonFromUrl(String url) throws IOException,
			JSONException {
		InputStream is = new URL(url).openStream();
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(is,
					Charset.forName("UTF-8")));
			String jsonText = readAll(rd);
			JSONObject json = new JSONObject(jsonText);
			return json;
		} finally {
			is.close();
		}
	}

}
